//3D显示 
<template>
  <el-row :gutter="6" style="height: 100%">
    <el-col :span="24" style="height: 100%">
      <div class="main" style="height: 100%">
        <div class="buttons" v-if="true">
          <!-- <button class="button" id="btnLoadVideo" @click="loadVideo">
            添加视频材质
          </button>
          <button
            class="button"
            id="btnSctPlaneAnimation"
            @click="sectionPlaneAnimation"
          >
            开启剖切动画
          </button>
          <button class="button" id="test" @click="test">test</button> -->

          <button class="button" id="btnLoadMap" @click="loadMap()">
            加载地图
          </button>
          <button
            class="button"
            id="btnShowMap"
            @click="showMap()"
            v-if="isMapLoaded"
          >
            隐藏地图
          </button>
          <button
            class="button"
            id="btnSetOpacity"
            @click="setOpacity()"
            v-if="isMapLoaded"
          >
            地图半透明
          </button>

          <button
            class="button"
            id="btnExcavationRegion"
            @click="showExcavationRegion()"
            v-if="isMapLoaded"
          >
            显示裁切区域
          </button>
        </div>
        <!-- 定义DOM元素，用于在该DOM元素中显示模型或图纸 -->
        <div class="model" id="domId" ref="mybox"></div>
      </div>
    </el-col>
  </el-row>
</template>


<script>
import EZUIKit from "@/assets/js/ezuikit.js";
export default {
  inject: ["reload"],
  components: {},

  // 初始化
  created() {
    console.log("woshuaxinla!!!!");

    this.$api.Tddisplay.getViewToken({
      code:
        "YmlOVVFDTWtNNlpaT2FkUFdMbkVHOWs3a2pjQmpvN006S1BuYWRLdjdSTWptWWQyTWJnMzVMZTF0eGpzVGsyQWI=",
      fileId: "2081735086467616",
    })
      .then((res) => {
        if (res.code === 200) {
          this.viewToken = res.data;
          // this.viewToken = "e13fa31bb98b42c086898d140758dd69";
          this.initData(res.data);
        } else {
          console.log("get comment data err res.msg:" + res.msg);
        }
      })
      .catch((err) => {
        console.log("get comment data err:" + err);
      });
  },

  mounted() {},

  watch: {},

  data() {
    return {
      viewToken: "",
      //三维视窗
      viewer3D: null,
      //数据是否已加载
      viewAdded: false,
      //视频是否已加载
      isRecPlaneAdded: false,
      //视频路径连接
      videoSrc:
        "http://39.106.121.254:5031/%E5%8C%97%E4%BA%AC%E5%9F%8E%E5%B8%82%E5%89%AF%E4%B8%AD%E5%BF%83%E7%AB%99%E7%BB%BC%E5%90%88%E4%BA%A4%E9%80%9A%E6%9E%A2%E7%BA%BD/%E5%A4%96%E4%B8%9A%E8%B4%A8%E9%87%8F/20200701115130790ssaa.mp4",
      // "http://39.106.121.254:5031/%E5%8C%97%E4%BA%AC%E5%9F%8E%E5%B8%82%E5%89%AF%E4%B8%AD%E5%BF%83%E7%AB%99%E7%BB%BC%E5%90%88%E4%BA%A4%E9%80%9A%E6%9E%A2%E7%BA%BD/%E5%A4%96%E4%B8%9A%E8%B4%A8%E9%87%8F/20200701115130790ssaa.mp4",
      //外部构件管理器
      extObjMng: null,
      // 外部构件的ID
      extObjId: null,
      // 构造视频材质对象
      material: null,

      //平面切割
      sectionPlane: null,
      originPt: { x: 0, y: 0, z: 7600 },
      planeDirection: { x: 0, y: 0, z: 1 }, //剖切方向
      sectionPlaneOffset: 500,
      isSectionPlaneAnimationActivated: false, //是否已经设置剖切动画
      animationId: null, //剖切动画的id

      //地图
      map: null,
      isMapLoaded: false,
      isMapShowed: false,
      isMapTranslucent: false,
      isMapLayerChanged: false,

      //开挖
      isExcavationRegionShowed: false,
    };
  },

  methods: {
    initData(viewToken) {
      // 初始化显示组件
      let options = new BimfaceSDKLoaderConfig();
      options.viewToken = viewToken;
      BimfaceSDKLoader.load(
        options,
        this.successCallback,
        this.failureCallback
      );
      this.dom4Show = this.$refs.mybox;
    },

    successCallback(viewMetaData) {
      let app;

      let that = this;

      if (viewMetaData.viewType == "3DView") {
        // ======== 判断是否为3D模型 ========
        // 获取DOM元素
        // var dom4Show = document.getElementById("domId");
        let dom4Show = this.$refs.mybox;

        let webAppConfig = new Glodon.Bimface.Application.WebApplication3DConfig();
        webAppConfig.domElement = dom4Show;
        // 创建WebApplication
        app = new Glodon.Bimface.Application.WebApplication3D(webAppConfig);
        // 添加待显示的模型
        app.addView(this.viewToken);
        // 从WebApplication获取viewer3D对象
        that.viewer3D = app.getViewer();
        // 监听添加view完成的事件
        that.viewer3D.addEventListener(
          Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded,
          function () {
            //自适应屏幕大小
            window.onresize = function () {
              that.viewer3D.resize(
                document.documentElement.clientWidth,
                document.documentElement.clientHeight - 40
              );
            };
            // var camera = {
            //   name: "persp",
            //   position: {
            //     x: -11354350.96835173,
            //     y: 13881979.024400208,
            //     z: 67179.25684516756,
            //   },
            //   target: {
            //     x: -10514568.072376572,
            //     y: 14563456.018563984,
            //     z: -471425.60657711886,
            //   },
            //   up: {
            //     x: 0.34615817544786204,
            //     y: 0.28090044221535554,
            //     z: 0.8951365589304376,
            //   },
            //   fov: 45,
            //   zoom: 1,
            //   version: 1,
            //   coordinateSystem: "world",
            // };
            // // 切换指定视角
            // that.viewer3D.setCameraStatus(camera);

            // 渲染3D模型
            that.viewer3D.render();

            //模型hover高亮
            that.viewer3D.enableMouseHoverHighlight();

            that.viewAdded = true;

            // 加载地图
            that.loadMap();
          }
        );
      }
    },

    failureCallback(error) {
      console.log(error);
    },

    //加载视频
    loadVideo() {
      if (!this.viewAdded || this.isRecPlaneAdded) {
        let target = this.viewer3D.getBoundingBoxById(this.extObjId);
        this.viewer3D.zoomToBoundingBox(target);
        return;
      }

      // 构造材质配置
      let materialConfig = new Glodon.Bimface.Plugins.Material.MaterialConfig();
      materialConfig.viewer = this.viewer3D;
      //视频路径
      materialConfig.src = this.videoSrc;
      materialConfig.textureType = "video";
      materialConfig.callback = this.animatecallback;
      // 构造视频材质对象
      this.material = new Glodon.Bimface.Plugins.Material.Material(
        materialConfig
      );

      //构造外部构件管理器
      if (!this.extObjMng) {
        this.extObjMng = new Glodon.Bimface.Plugins.ExternalObject.ExternalObjectManager(
          this.viewer3D
        );
      }
      let recPlane = this.createPlane();
      // 将平面对象添加为外部构件，并获取其ID
      this.extObjMng.addObject("recPlane", recPlane);
      this.extObjId = this.extObjMng.getObjectIdByName("recPlane");
      // 将平面对象移动并旋转至指定位置
      this.extObjMng.offset(this.extObjId, { x: -3100, y: -4350, z: 7450 });
      this.extObjMng.rotateX(this.extObjId, Math.PI / 2);
      // 缩放至平面构件
      let boundingBox = this.viewer3D.getBoundingBoxById(this.extObjId);
      this.viewer3D.zoomToBoundingBox(boundingBox);
      this.viewAdded = true;
      this.isRecPlaneAdded = true;
    },
    //更新视频播放
    videoPlayAnimate() {
      requestAnimationFrame(this.videoPlayAnimate);
      // this.viewer3D.render();
    },
    animatecallback() {
      //将外部构件赋予视频材质
      this.material.overrideComponentsMaterialById([this.extObjId]);
      this.videoPlayAnimate();
    },
    // 构造矩形平面
    createPlane() {
      // 定义矩形平面的点位
      let pt1 = {
        x: 0,
        y: 0,
        z: 0,
      };
      let pt2 = {
        x: 2500,
        y: 1100,
        z: 0,
      };
      // 设置平面填充色
      let planeColor = new Glodon.Web.Graphics.Color("#32D3A6", 0.4);
      // 构造矩形平面，并赋予颜色材质
      let rectanglePlane = new Glodon.Bimface.Plugins.Geometry.Plane(pt1, pt2);
      rectanglePlane.setColor(planeColor);
      rectanglePlane.clearBorder();
      return rectanglePlane;
    },

    // 构造剖切面并设置初始状态

    createSectionPlane() {
      if (!this.viewAdded || this.sectionPlane) {
        return;
      }
      let sectionPlaneConfig = new Glodon.Bimface.Plugins.Section.SectionPlaneConfig();
      sectionPlaneConfig.viewer = this.viewer3D;
      this.sectionPlane = new Glodon.Bimface.Plugins.Section.SectionPlane(
        sectionPlaneConfig
      );
      this.sectionPlane.setPlane(
        Glodon.Bimface.Plugins.Section.SectionPlanePlane.Z
      );
      this.sectionPlane.setDirection(
        Glodon.Bimface.Plugins.Section.SectionPlaneDirection.Forward
      );
      this.sectionPlane.setPositionByPlane(
        this.originPt,
        this.planeDirection,
        this.sectionPlaneOffset
      );
      this.sectionPlane.setObjectsByObjectData([
        {
          categoryId: "-2000011",
          family: "基本墙",
        },
        {
          categoryId: "-2001330",
        },
      ]);
      this.sectionPlane.hidePlane();
    },
    // 剖切面移动动画
    sectionPlaneAnimate() {
      this.animationId = requestAnimationFrame(this.sectionPlaneAnimate);
      this.sectionPlaneOffset += 50;
      if (this.sectionPlaneOffset > 3500) {
        this.sectionPlaneOffset = 500;
      }
      this.sectionPlane.setPositionByPlane(
        this.originPt,
        this.planeDirection,
        this.sectionPlaneOffset
      );
      // this.viewer3D.render();
    },

    // 添加剖切面移动动画
    sectionPlaneAnimation() {
      if (!this.viewAdded || !this.sectionPlane) {
        return;
      }
      if (!this.isSectionPlaneAnimationActivated) {
        this.sectionPlaneAnimate();
        this.setButtonText("btnSctPlaneAnimation", "停止剖切动画");
      } else {
        cancelAnimationFrame(this.animationId);
        sectionPlaneOffset = 500;
        this.sectionPlane.setPositionByPlane(
          this.originPt,
          this.planeDirection,
          this.sectionPlaneOffset
        );
        // this.viewer3D.render();
        this.setButtonText("btnSctPlaneAnimation", "开启剖切动画");
      }
      this.isSectionPlaneAnimationActivated = !this
        .isSectionPlaneAnimationActivated;
    },

    // ************************** 按钮文字 **************************
    setButtonText(btnId, text) {
      var dom = document.getElementById(btnId);
      if (dom != null && dom.nodeName == "BUTTON") {
        dom.innerText = text;
      }
    },

    // 添加构件嵌套关系
    loadMap() {
      if (!this.viewAdded) {
        return;
      }
      if (!this.isMapLoaded) {
        // 构造地图配置项
        var mapConfig = new Glodon.Bimface.Plugins.TileMap.MapConfig();
        mapConfig.viewer = this.viewer3D;
        // 设置模型载入的基点
        mapConfig.basePoint = {
          x: 478942.29,
          y: 304167.52,
        };
        // 设置模型载入基点所对应的经纬度
        mapConfig.modelPosition = [116.110936916, 39.909960784];
        // 设置模型的旋转弧度值
        mapConfig.modelRotationZ = (0 * Math.PI) / 180;
        // 设置模型零零标高对应的高程值，单位为米
        mapConfig.modelAltitude = -2;
        // 设置不开启DEM
        mapConfig.enableElevationModel = false;
        // 设置地图透明度
        // mapConfig.opacity = 1.0;
        // 构造地图对象
        this.map = new Glodon.Bimface.Plugins.TileMap.Map(mapConfig);
        // 设置地图类型为天地图的卫星影像，天地图key可在http://lbs.tianditu.gov.cn/server/MapService.html申请
        this.map.setMapSource({
          url:
            "http://t0.tianditu.gov.cn/img_w/wmts?tk=4e51b736b9d32aa01b45853115fd360a",
          provider: "Tianditu",
          credit: Glodon.Bimface.Common.Credit.Tianditu,
        });

        this.excavationMap();
        this.setButtonText("btnLoadMap", "卸载地图");
        this.isMapShowed = true;
      } else {
        this.map.destroy();
        this.setButtonText("btnLoadMap", "加载地图");
        this.setButtonText("btnShowMap", "隐藏地图");
        this.isMapLayerChanged = false;
      }
      // this.viewer3D.render();
      this.isMapLoaded = !this.isMapLoaded;
    },

    ///加载地图
    showMap() {
      if (!this.isMapShowed) {
        this.map.show();
        this.setButtonText("btnShowMap", "隐藏地图");
      } else {
        this.map.hide();
        this.setButtonText("btnShowMap", "显示地图");
      }
      // this.viewer3D.render();
      this.isMapShowed = !this.isMapShowed;
    },
    setOpacity() {
      if (!this.isMapShowed) {
        this.setButtonText("btnSetOpacity", "地图半透明");
      }
      if (!this.isMapTranslucent) {
        this.map.setOpacity(0.2);
        this.setButtonText("btnSetOpacity", "取消半透明");
      } else {
        this.map.setOpacity(1);
        this.setButtonText("btnSetOpacity", "地图半透明");
      }
      // this.viewer3D.render();
      this.isMapTranslucent = !this.isMapTranslucent;
    },

    excavationMap() {
      var regionPts_1 = [
        {
          x: 479011.7,
          y: 304902.56,
          z: 0,
        },
        {
          x: 479067.72,
          y: 304891.54,
          z: 0,
        },
        {
          x: 478956.68,
          y: 304386.45,
          z: 0,
        },
        {
          x: 479010.3,
          y: 304343.03,
          z: 0,
        },
      ];

      if (this.map) {
        console.log();
        this.map.addExcavationRegion("excavationRegion_1", regionPts_1);
        this.map.showExcavationRegionsById(["excavationRegion_1"]);
        this.isExcavationRegionShowed = true;
      }
    },

    showExcavationRegion() {
      if (!this.viewAdded) {
        console.log("what");
        return;
      }
      if (!this.isExcavationRegionShowed) {
        console.log("zou sa");
        this.map.showExcavationRegionsById(["excavationRegion_1"]);
        this.setButtonText("btnExcavationRegion", "隐藏裁切区域");
      } else {
        console.log("yin cang");
        this.map.hideExcavationRegionsById(["excavationRegion_1"]);
        this.setButtonText("btnExcavationRegion", "显示裁切区域");
      }
      this.isExcavationRegionShowed = !this.isExcavationRegionShowed;
    },
  },

  computed: {},
};
</script>
<style lang='less' scoped>
.main {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
  width: 100%;

  .buttons {
    font-size: 0;
    position: absolute;
    z-index: 999;
    justify-content: center;
    text-align: center;
    right: 8%;
  }

  .button {
    margin: 5px 0 5px 5px;
    width: 100px;
    height: 30px;
    border-radius: 3px;
    border: none;
    background: #11dab7;
    color: #ffffff;
    outline: none;
  }
}
.model {
  flex: 1;
}
</style>